<template>
  <div>
    <!-- 资产迁移申请表单弹窗 -->
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
    >
      <el-descriptions
        class="margin-top"
        title=""
        :column="2"
        size="large"
        v-show="props.isReadonly"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.assetName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备编码</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.assetCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">经办人</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.handlerPersonName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">迁移时间</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.migrationTime }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">迁移原因</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.migrationReason }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">迁出部门</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.originalDepartmentName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">迁入部门</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.targetDepartmentName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">原使用人</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.originalUsingPersonName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">新使用人</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.targetUsingPersonName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">迁出位置</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.originalLocationName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">迁入位置</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            {{ formData.targetLocationName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">状态</div>
          </template>
          <div style="width: 50%; word-break: break-all">
            <el-tag v-if="formData.migrationStatue == 0" type="info"
              >取消</el-tag
            >
            <el-tag v-if="formData.migrationStatue == 1">新建</el-tag>
            <el-tag v-if="formData.migrationStatue == 2" type="success">
              已确认
            </el-tag>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="160"
        v-show="!props.isReadonly"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="assetId" label-width="80px">
              <el-input
                :disabled="props.type != 'add'"
                v-model="formData.assetName"
                placeholder="请选择设备"
                @focus="openSelectDialog()"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="assetCode" label-width="80px">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.assetCode"
                placeholder="请选择设备"
                disabled
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="经办人"
              prop="handlerPersonId"
              label-width="80px"
            >
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.handlerPersonId"
                placeholder="请选择经办人"
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                clearable
                @change="(e) => changePerson(e, '经办人')"
              >
                <el-option
                  v-for="item in handlerPersonList"
                  :label="`${item.firstName}`"
                  :value="`${item.id}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="迁移时间"
              prop="migrationTime"
              label-width="80px"
            >
              <el-date-picker
                v-model="formData.migrationTime"
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                type="datetime"
                placeholder="请选择迁移时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="迁移原因"
              prop="migrationReason"
              label-width="80px"
            >
              <el-input
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                v-model="formData.migrationReason"
                type="textarea"
                placeholder="请输入迁移原因"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="迁出部门"
              prop="originalDepartmentId"
              label-width="80px"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.originalDepartmentName"
                :placeholder="
                  formData.assetId ? '设备当前无使用部门' : '请选择设备'
                "
                disabled
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="迁入部门"
              prop="targetDepartmentId"
              label-width="80px"
            >
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids)"
                @change-data="
                  (datas) =>
                    (formData.targetDepartmentName = datas.organizationName)
                "
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                :data="dataObject('target')"
                :selectData="formData.targetDepartmentName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="原使用人"
              prop="originalUsingPersonId"
              label-width="80px"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.originalUsingPersonName"
                :placeholder="
                  formData.assetId ? '设备当前无使用人' : '请选择设备'
                "
                disabled
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="新使用人"
              prop="targetUsingPersonId"
              label-width="80px"
            >
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.targetUsingPersonId"
                placeholder="请选择新使用人"
                clearable
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                @change="(e) => changePerson(e, '新使用人')"
              >
                <el-option
                  v-for="item in targetPersonList"
                  :label="`${item.firstName}`"
                  :value="`${item.id}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="迁出位置"
              prop="originalLocationId"
              label-width="80px"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.originalLocationName"
                :placeholder="
                  formData.assetId ? '设备当前无位置' : '请选择设备'
                "
                disabled
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="迁入位置"
              prop="targetLocationId"
              label-width="80px"
            >
              <el-tree-select
                placeholder="请输入设备位置"
                style="width: 300px"
                filterable
                v-if="!props.isReadonly"
                v-model="formData.targetLocationId"
                :data="locationInfoTree"
                node-key="id"
                clearable
                :props="{ label: 'locationName', children: 'nodes' }"
                check-strictly
                :disabled="
                  formData.migrationStatue !== '' &&
                  formData.migrationStatue != 1
                "
                @node-click="changeTargetLocation"
                :render-after-expand="false"
                @change="handelTargetLocation"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly && props.type != 'confirm'"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button
            v-if="!props.isReadonly && props.type == 'confirm'"
            type="primary"
            :loading="loading"
            @click="handleConfirm"
            >审核确认</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <devicechangestatus-select
      :visible="selectDialog.visible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMASSETMIGRATIONAPPLYADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  type: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  assetId: [
    { required: true, message: "请选择设备", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  migrationReason: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  migrationTime: [],
  handlerPersonId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  migrationStatue: [],
  originalDepartmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  targetDepartmentId: [
    { required: true, message: "请选择部门", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  originalUsingPersonId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  targetUsingPersonId: [
    { required: true, message: "请选择使用人", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  originalLocationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  targetLocationId: [
    { required: true, message: "请选择位置", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  migrationReason: "",
  migrationTime: "",
  handlerPersonId: "",
  handlerPersonName: "",
  migrationStatue: "",
  originalDepartmentId: "",
  originalDepartmentName: "",
  targetDepartmentId: "",
  targetDepartmentName: "",
  originalUsingPersonId: "",
  originalUsingPersonName: "",
  targetUsingPersonId: "",
  targetUsingPersonName: "",
  originalLocationId: "",
  originalLocationName: "",
  targetLocationId: "",
  targetLocationName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetId,
        assetCode,
        assetName,
        migrationReason,
        migrationTime,
        handlerPersonId,
        handlerPersonName,
        migrationStatue,
        originalDepartmentId,
        originalDepartmentName,
        targetDepartmentId,
        targetDepartmentName,
        originalUsingPersonId,
        originalUsingPersonName,
        targetUsingPersonId,
        targetUsingPersonName,
        originalLocationId,
        originalLocationName,
        targetLocationId,
        targetLocationName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetId,
        assetCode,
        assetName,
        migrationReason,
        migrationTime,
        handlerPersonId,
        handlerPersonName,
        migrationStatue,
        originalDepartmentId,
        originalDepartmentName,
        targetDepartmentId,
        targetDepartmentName,
        originalUsingPersonId,
        originalUsingPersonName,
        targetUsingPersonId,
        targetUsingPersonName,
        originalLocationId,
        originalLocationName,
        targetLocationId,
        targetLocationName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      getUserList(targetDepartmentId).then((res) => {
        targetPersonList.value = res;
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.migrationReason = "";
  formData.migrationTime = "";
  formData.handlerPersonId = "";
  formData.handlerPersonName = "";
  formData.migrationStatue = "";
  formData.originalDepartmentId = "";
  formData.originalDepartmentName = "";
  formData.targetDepartmentId = "";
  formData.targetDepartmentName = "";
  formData.originalUsingPersonId = "";
  formData.originalUsingPersonName = "";
  formData.targetUsingPersonId = "";
  formData.targetUsingPersonName = "";
  formData.originalLocationId = "";
  formData.originalLocationName = "";
  formData.targetLocationId = "";
  formData.targetLocationName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 资产迁移申请保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamassetmigrationapply/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

/** 资产迁移申请保存提交 */
function handleConfirm() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "审核确认";
      await request({
        url: "/eam/eamassetmigrationapply/confirm",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function openSelectDialog() {
  changeVisible(true, null);
}

//设备显隐
const selectDialog = ref({
  visible: false,
});
const changeVisible = (val: boolean, data: any) => {
  if (data) {
    console.log(data);
    formData.assetId = data.id;
    formData.assetCode = data.assetCode;
    formData.assetName = data.assetName;
    formData.originalLocationId = data.locationId;
    formData.originalLocationName = data.locationName;
    formData.originalUsingPersonId = data.usingPersonId;
    formData.originalUsingPersonName = data.usingPersonName;
    formData.originalDepartmentId = data.usingDepartmentId;
    formData.originalDepartmentName = data.usingDepartmentName;
  }
  selectDialog.value.visible = val;
};
const handlerPersonList = ref([]);
const targetPersonList = ref([]);

const getUserList = async (departmentId: string | null) => {
  const { data } = await request({
    url: "/system/sysUser/getList ",
    method: "post",
    data: {
      enabled: 1,
      departmentId: departmentId,
    },
  });
  return Promise.resolve(data);
};

const changeTargetDept = async (id) => {
  getUserList(id).then((res) => {
    targetPersonList.value = res;
  });
};
const changePerson = (e: any, name: string) => {
  if (e) {
    if (name == "经办人") {
      handlerPersonList.value.forEach((item: any) => {
        if (item.id == e) {
          formData.handlerPersonName = item.firstName;
        }
      });
    }
    if (name == "新使用人") {
      targetPersonList.value.forEach((item: any) => {
        if (item.id == e) {
          formData.targetUsingPersonName = item.firstName;
        }
      });
    }
  }
};

const dataObject = () => {
  return {
    name: "迁入部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string) {
  formData.targetDepartmentId = ids;
  changeTargetDept(ids);
}

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 点击位置树
const changeTargetLocation = (e) => {
  if (e) {
    formData.targetLocationId = e.id;
    formData.targetLocationName = e.locationName;
  } else {
    formData.targetLocationId = "";
    formData.targetLocationName = "";
  }
};

const handelTargetLocation = (e) => {
  if (!e) {
    formData.targetLocationId = "";
    formData.targetLocationName = "";
  }
};
onMounted(() => {
  getUserList(null).then((res) => {
    handlerPersonList.value = res;
  });
  getLocationInfoTree();
});
</script>
